package com.example.loginstructuredemo.http;

import com.example.loginstructuredemo.DemoApplication;
import com.example.loginstructuredemo.UrlConstants;

import java.io.File;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络请求方式
 * Created by Alex on 2016/10/13.
 */

public class HttpMethodsRetrofit {

	//短缓存有效期为1分钟
	public static final int CACHE_STALE_SHORT = 60;
	//长缓存有效期为7天
	public static final int CACHE_STALE_LONG = 60 * 60 * 24 * 7;

	public static final String CACHE_CONTROL_AGE = "Cache-Control: public, max-age=";

	//查询缓存的Cache-Control设置，为if-only-cache时只查询缓存而不会请求服务器，max-stale可以配合设置缓存失效时间
	public static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_LONG;
	//查询网络的Cache-Control设置，头部Cache-Control设为max-age=0时则不会使用缓存而请求服务器
	public static final String CACHE_CONTROL_NETWORK = "max-age=0";

	private static final int DEFAULT_TIMEOUT = 5;

	private static Retrofit retrofit;

	private static OkHttpClient mOkHttpClient;

	public static HttpMethodsRetrofit build() {
		return new HttpMethodsRetrofit();
	}

	private HttpMethodsRetrofit() {
		initOkHttpClient();

		retrofit = new Retrofit.Builder()
				.client(mOkHttpClient)
				.addConverterFactory(GsonConverterFactory.create())
				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
				.baseUrl(UrlConstants.BASE_URL)
				.build();
	}

	public static Retrofit getRetrofit() {
		return retrofit;
	}

	private void initOkHttpClient() {
		if (mOkHttpClient == null) {
			synchronized (HttpMethodsRetrofit.class) {
				if (mOkHttpClient == null) {
					// 指定缓存路径,缓存大小100Mb
//					Cache cache = new Cache(new File(DemoApplication.getContext().getCacheDir(), "HttpCache"),
//							1024 * 1024 * 100);
					File httpCacheDirectory = new File(DemoApplication.getContext().getCacheDir(), "httplog");
					mOkHttpClient = new OkHttpClient().newBuilder()
							.cache(new Cache(httpCacheDirectory,10 * 1024 * 1024))
							//有网络的拦截器
							.addNetworkInterceptor(HttpInterceptor.REWRITE_RESPONSE_INTERCEPTOR)
							//没有网络的拦截器
							.addInterceptor(HttpInterceptor.REWRITE_RESPONSE_INTERCEPTOR_OFFLINE)
//							.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
							.build();
//							.addInterceptor(new Interceptor() {
//								@Override
//								public Response intercept(Chain chain) throws IOException {
//									Request request = chain.request()
//											.newBuilder()
//											.addHeader("epdToken", "")
//											.addHeader("epdDevice", "android")
//											.addHeader("epdVersion", "2.5.2").build();
//									return chain.proceed(request);
//								}
//							}).build();

				}
			}
		}
	}
}
